package com.example.learningnote.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.example.learningnote.MainActivity;

public class FileDownloadService extends Service {
    private static final String TAG = "FileDownloadService";
    private static final String CHANNEL_ID = "DownloadChannel";
    private static final int NOTIFICATION_ID = 1;
    private boolean isDownloading = false;
    public static final String ACTION_DOWNLOAD_COMPLETE = "com.example.downloadapp.DOWNLOAD_COMPLETE";
    public static final String EXTRA_FILE_URL = "file_url";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service Created");
        createNotificationChannel();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service Started");
        String fileUrl = intent.getStringExtra("file_url");
        if (fileUrl != null && !isDownloading) {
            startForegroundNotification();
            startDownload(fileUrl);
        }
        return START_STICKY; // Service 被杀死后尝试重启
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "File Download Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    @SuppressLint("ForegroundServiceType")
    private void startForegroundNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("File Download")
                .setContentText("Downloading file...")
                .setSmallIcon(android.R.drawable.ic_menu_save)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(NOTIFICATION_ID, notification);
    }

    private void startDownload(String fileUrl) {
        isDownloading = true;
        new Thread(() -> {
            try {
                // 模拟下载过程（实际中可使用 OkHttp 或 DownloadManager）
                Log.d(TAG, "Downloading: " + fileUrl);
                Thread.sleep(5000); // 模拟 5 秒下载
                Log.d(TAG, "Download completed");

                // 发送自定义广播
                Intent broadcastIntent = new Intent(ACTION_DOWNLOAD_COMPLETE);
                broadcastIntent.putExtra(EXTRA_FILE_URL, fileUrl);
                sendBroadcast(broadcastIntent);

                // 发送下载完成通知
                Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentTitle("Download Complete")
                        .setContentText("File downloaded successfully")
                        .setSmallIcon(android.R.drawable.ic_dialog_info)
                        .build();

                NotificationManager manager = getSystemService(NotificationManager.class);
                manager.notify(NOTIFICATION_ID + 1, notification);

                // 停止服务
                stopForeground(true);
                stopSelf();
            } catch (InterruptedException e) {
                Log.e(TAG, "Download interrupted", e);
            } finally {
                isDownloading = false;
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service Destroyed");
        isDownloading = false;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null; // 不需要绑定
    }
}

